import java.util.ArrayList;
import java.util.List;

public class CombinationSum3 {

    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        int[] nums = {1,2,3,4,5,6,7,8,9};
        process(nums, 0, k, n);
        return ans;
    }

    public void process(int[] nums, int i, int k, int n) {
        if (n == 0 || k == 0) {
            if (n == 0 && k == 0) {
                ans.add(new ArrayList<>(list));
            }
            return;
        }
        if (i == nums.length) return;

        process(nums, i + 1, k, n);
        if (k > 0 && n - nums[i] >= 0) {
            list.add(nums[i]);
            process(nums, i + 1, k - 1, n - nums[i]);
            list.remove(list.size() - 1);
        }
    }
}
